#include "File.h"
#include <iostream>

namespace mkuz
{
    namespace io
    {
        File::File(const std::string & path) : _path(path)
        {
            _stream.exceptions(std::ios_base::failbit|std::ios_base::badbit|std::ios_base::eofbit);
        }
        
        void File::Read(char * data, size_t & size)
        {
            _stream.open(_path.c_str(), std::ios::in|std::ios::binary);
            _stream.seekg(0, std::ios::end);
            size_t size0 = _stream.tellg();
            _stream.seekg(0, std::ios::beg);
            if (data != 0)
            {
                _stream.read(data, std::min(size, size0));
            }
            size = size0;
            _stream.close();
        }
        
        void File::Write(const char * data, size_t size, bool append)
        {
            if (data == 0)
                throw std::fstream::failure("Pointer to a buffer is null. ");
            if (append)
                _stream.open(_path.c_str(), std::ios::out | std::ios::binary | std::ios::binary | std::ios::app);
            else
                _stream.open(_path.c_str(), std::ios::out | std::ios::binary | std::ios::binary);
            _stream.write(data, size);
            _stream.close();
        }
    }
}

